package org.sith.taskrunner.listeners;

import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.UserThreadKeeper;
import org.sith.taskrunner.managedbeans.Urls;
import org.sith.taskrunner.managedbeans.UserManagedBean;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import java.util.Locale;


public class AuthenticationPhaseListener implements PhaseListener {


    public void afterPhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();

        ExternalContext extContext = context.getExternalContext();
        User user = (User) extContext.getSessionMap().get(UserManagedBean.USER_SESSION_KEY);
        if (user != null) {
            UserThreadKeeper.setThreadUser(user);
            return;
        } else {
            if (requestingSecureView(context)) {
                context.responseComplete();
                context.getApplication().
                        getNavigationHandler().handleNavigation(context,
                        null,
                        Urls.USER_LOGIN_OUTCOME);
            }
        }
    }

  
    public void beforePhase(PhaseEvent event) {
    }

 
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
    
    private boolean requestingSecureView(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();
        String path = extContext.getRequestPathInfo();
        return (!"/login.jsp".equals(path));
    }

}